package com.web.config;

import com.web.handler.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.session.CompositeSessionAuthenticationStrategy;
import org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy;
import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy;
import org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy;
import org.springframework.security.web.session.ConcurrentSessionFilter;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.security.web.session.SimpleRedirectSessionInformationExpiredStrategy;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;

import java.util.Arrays;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
@Slf4j
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    SecurityMetadataSourceService securityMetadataSourceService;
    @Autowired
    CustomUserService customUserService;
    @Autowired
    MyAccessDecisionManage myAccessDecisionManage;
    @Bean
    public AuthenticationProvider daoAuthenticationProviderImpl(){
        AuthenticationProvider daoAuthenticationProvider=new AuthenticationProvider();
        daoAuthenticationProvider.setPasswordEncoder(new Md5PasswordEncoder());
        daoAuthenticationProvider.setUserDetailsService(customUserService);
        daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
        return daoAuthenticationProvider;
    }
    @Bean
    public MyFilterSecurityInterceptor myFilterSecurityInterceptor() {
        MyFilterSecurityInterceptor myFilterSecurityInterceptor = new MyFilterSecurityInterceptor();
        myFilterSecurityInterceptor.setSecurityMetadataSourceService(securityMetadataSourceService);
        myFilterSecurityInterceptor.setAccessDecisionManager(myAccessDecisionManage);
        return myFilterSecurityInterceptor;
    }
    @Bean
    public MyLogoutSuccessHandler myLogoutSuccessHandler(){
        MyLogoutSuccessHandler myLogoutSuccessHandler=new MyLogoutSuccessHandler();
        return myLogoutSuccessHandler;
    }
    @Bean
    public MyLoginSuccessHandler myLoginSuccessHandler(){
        MyLoginSuccessHandler myLoginSuccessHandler=new MyLoginSuccessHandler();
        myLoginSuccessHandler.setDefaultTargetUrl("/index");
        myLoginSuccessHandler.setAlwaysUseDefaultTargetUrl(true);
        return myLoginSuccessHandler;
    }

    @Bean
    public KdUsernamePasswordAuthenticationFilter kdUsernamePasswordAuthenticationFilter() throws Exception {
        KdUsernamePasswordAuthenticationFilter kdUsernamePasswordAuthenticationFilter = new KdUsernamePasswordAuthenticationFilter();
        kdUsernamePasswordAuthenticationFilter.setAuthenticationManager(this.authenticationManager());
        kdUsernamePasswordAuthenticationFilter.setAuthenticationSuccessHandler(myLoginSuccessHandler());
        kdUsernamePasswordAuthenticationFilter.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler("/login?error"));
        kdUsernamePasswordAuthenticationFilter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy());
        return kdUsernamePasswordAuthenticationFilter;
    }
    @Bean
    public SessionRegistry sessionRegistry(){
        return new SessionRegistryImpl();
    }
    //session失效跳转
    private SessionInformationExpiredStrategy sessionInformationExpiredStrategy() {
        return new SimpleRedirectSessionInformationExpiredStrategy("/login?expired");
    }
    @Bean
    public CompositeSessionAuthenticationStrategy sessionAuthenticationStrategy(){
        ConcurrentSessionControlAuthenticationStrategy concurrentSessionControlAuthenticationStrategy=new ConcurrentSessionControlAuthenticationStrategy(sessionRegistry());
        concurrentSessionControlAuthenticationStrategy.setMaximumSessions(3);
        concurrentSessionControlAuthenticationStrategy.setExceptionIfMaximumExceeded(false);
        SessionFixationProtectionStrategy sessionFixationProtectionStrategy=new SessionFixationProtectionStrategy();
        RegisterSessionAuthenticationStrategy registerSessionStrategy = new RegisterSessionAuthenticationStrategy(sessionRegistry());
        CompositeSessionAuthenticationStrategy sessionAuthenticationStrategy=new CompositeSessionAuthenticationStrategy(
                Arrays.asList(concurrentSessionControlAuthenticationStrategy,sessionFixationProtectionStrategy,registerSessionStrategy));
        return sessionAuthenticationStrategy;
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //addFilterBefore(kdUsernamePasswordAuthenticationFilter(),UsernamePasswordAuthenticationFilter.class)
        http.headers().frameOptions().disable();
        http.
                addFilterAt(kdUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class).addFilterBefore(myFilterSecurityInterceptor(), FilterSecurityInterceptor.class).
                addFilterAt(new ConcurrentSessionFilter(sessionRegistry(),sessionInformationExpiredStrategy()),ConcurrentSessionFilter.class).authorizeRequests()
                .antMatchers("/app/**","/assets/**", "/swagger/**","/default/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/needlogin")
                .permitAll()
                .and()
                .logout().invalidateHttpSession(true).logoutSuccessHandler(myLogoutSuccessHandler())
                .permitAll();
        http.csrf().ignoringAntMatchers("/app/**","/default/**");
        //.and().sessionManagement().maximumSessions(1).expiredUrl("/login?expired").sessionRegistry(sessionRegistry()).expiredSessionStrategy();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
//        auth
//                .inMemoryAuthentication()
//                .withUser("admin").password("111111").roles("USER");
        auth.authenticationProvider(daoAuthenticationProviderImpl());
//        auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery("select username,password,enabled from users where username = ? ").
//                passwordEncoder(new Md5PasswordEncoder());
    }

}